package com.struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.struts.config.XmlBean;
import com.struts.form.Form;
import com.struts.form.FullForm;

/**
 * Servlet implementation class Action
 */
public class ActionServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		String path = request.getServletPath().replace(".do", "");
		Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		
		XmlBean xml = map.get(path);
		String beanClass = xml.getBeanClass();
		Form form = FullForm.full(request, beanClass);
		
		String actionClass = xml.getActionClass();
		Action action = null;
		String url = null;
		
		try {
			
			Class clazz = Class.forName(actionClass);
			action = (Action)clazz.newInstance();
			url = action.execute(request, response, form, xml.getActionForward());
			
		} catch (Exception e) {
			
			System.out.println("错误：控制器异常");
			e.printStackTrace();
		}
		
		RequestDispatcher rd = request.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		this.doGet(request, response);
	}

}
